<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { useCourseStore } from '@/store/kg/course';
import { useAdminUserStore } from '@/store/system/adminUser';
import type { PropType } from 'vue';

const props = defineProps({
  courseId: { type: String as PropType<string> },
});

const courseStore = useCourseStore();
const adminUserStore = useAdminUserStore();
// 分配的用户
const assignUsers = ref<Array<string>>([]);

/**
 * 获取课程已授权的用户列表
 */
const getUsersByCourseId = async () => {
  // 初始化值为空数组
  assignUsers.value = [];

  // 根据课程id查询授权用户信息
  const courseId = props.courseId;
  if (courseId) {
    const users = await courseStore.getCoursePermissions(courseId);
    // 提取用户ID
    assignUsers.value = users.map((user: any) => String(user.userId));
  }
};

onMounted(() => {
  // 获取所有用户
  adminUserStore.getAdminUserList();
});

// 监听课程ID变化，当ID变化时重新获取课程权限
watch(() => props.courseId, (newVal) => {
  if (newVal) {
    getUsersByCourseId();
  }
}, { immediate: true });

defineExpose({ assignUsers });
</script>

<template>
  <div class="flex justify-center">
    <el-transfer
      v-model="assignUsers"
      :button-texts="['收回', '分配']"
      :data="adminUserStore.datalist.map(user => ({ key: String(user.id), label: user.nickname || user.username }))"
      filter-placeholder="搜索用户"
      :format="{ noChecked: `总共 \${total}`, hasChecked: '\${checked}/\${total}' }"
      :titles="['未分配', '已分配']"
      class="m-3"
      filterable
    />
  </div>
</template>
